/*
 * 轮播图插件，支持在手机上滑动
 * Author: rguanghui.stupid@gmail.com, rguanghui.sinaapp.com
 * Update: 2014.07.03
 * Verson: 1.2
 * @param container {String|object} 要添加轮播图层的id或dom
 * @param data {Array}  轮播图需要的数组，数组里的每一个值是一个对象
 * data[index].title    每个图片附带的标题
 * data[index].imageURL 图片路径
 * data[index].linkURL  图片链接地址
 * 其他说明：WP手机不含有touch事件，可用其独有的事件进行监听绑定，暂时不管。
 *         为了视觉效果，自动轮播时轮播图是循环播放的，但用手滑动时却是单向的。
 * 需要引入一点css
 * .slide { position: relative; -webkit-backface-visibility: hidden; backface-visibility: hidden; overflow: hidden; width: 100%; height: 11em; }
 * .slide .slide-image { height: 100%; }
 * .slide .slide-image li { position: relative; float: left; width: 100%; height: 100%; }
 * .slide .slide-image img { width: 100%; }
 * .slide .slide-image h3 { position: absolute; bottom: 0; width: 100%; height: 2em; line-height: 2em; background-color: rgba(0,0,0,.6); color: #fff; text-align: left; font-size: 1rem; }
 * .slide .slide-number { position: absolute; bottom: .5em; right: .5em; }
 * .slide .slide-number li { float: left; margin-right: .3em; width: 1em; height: 1em; background-color: #fff; border-radius: 50%; }
 *  .slide .slide-number li.current { background-color: #f90; }
 */

(function(window, undefined){
  
  var template = "<li><a href='{{linkURL}}'><img src='{{imageURL}}'><h3>{{title}}</h3></a></li>";
  
  var slide = function ( container, data ) {
    data || ( data = [] );
    this.container = ( typeof container === "string" ) ? document.getElementById( container ) : container;
    this.htmlArray = [];
    this.init( data );
  };
  
  slide.prototype = {
    init: function( data ) {
      for(var i = 0, item; item = data[i]; i++) {
        var html = template.replace( /{{([^}}]+)?}}/g, function( s0, s1 ) {
         return item[s1] || "";
        });
        this.htmlArray.push( html );
      };
      this.length = data.length;
      this.width = this.container.offsetWidth;
      this.index = 0;
      this.startX = this.startY = 0;
      this.translateX = 0;
      this.moved = false;
      this.play = null;
      this.interval = 3000;
      this.createHTML();
      this.bindTouch();
      this.autoPlay();
    },
    createHTML: function() {
      // 创建轮播结构，插入
      this.ul = document.createElement( "ul" );
      this.ul.setAttribute( "class", "slide-image" );
      this.ul.innerHTML = this.htmlArray.join( "" );
      this.ul.style.webkitTransform = "translateX(0)";
      this.ul.style.msTransform = "translateX(0)";
      this.ul.style.transform = "translateX(0)";
      this.ul.style.webkitTransition = "-webkit-transform .8s ease-in-out";
      this.ul.style.msTransition = "-ms-transform .8s ease-in-out";
      this.ul.style.transition = "transform .8s ease-in-out";
      this.ul.style.width = this.width * this.length + "px";
      this.container.innerHTML = "";
      this.container.appendChild( this.ul );
      this.li = this.ul.querySelectorAll( "li" );
      this.images = this.ul.querySelectorAll( "img" );
      this.numbers = document.createElement( "ul" );
      // 创建轮播指示数字
      var numHTML = "";
      this.numbers.setAttribute( "class", "slide-number" );
      for ( var i = 0, li; li = this.li[i]; i++ ) {
        li.style.width = this.width + "px";
        numHTML += "<li class=" + ( i === 0 ? 'current' : '' ) + "></li>";
      };
      this.numbers.innerHTML = numHTML;
      this.container.appendChild( this.numbers );
    },
    bindTouch: function() {
      // 绑定触摸事件
      var self = this;
      this.container.addEventListener("touchstart", function( event ) {
        self.touchStart.call( self, event ); 
      }, false);
      this.container.addEventListener("touchmove", function( event ) {
        self.touchMove.call( self, event );
      }, false);
      this.container.addEventListener("touchend", function( event ) {
       self.touchEnd.call( self, event );
      }, false);
      this.container.addEventListener("touchcancel", function( event ) {
        self.touchEnd.call( self, event );
      }, false);
    },
    autoPlay: function() {
      this.play = setInterval( (function( _this ) {
        return function() {
          _this.index++;
          // 自动滚动的时候循环滚动
          ( _this.index < 0 ) && ( _this.index = _this.li.length-1 );
          ( _this.index >= _this.li.length ) && ( _this.index = 0 );
          _this.move();
        }
      })(this), this.interval );
    },
    move: function( target ) {
      for ( var i = 0; item = this.numbers.children[i]; i++ ) {
        item.classList.remove( "current" );
      };
      this.numbers.children[this.index].classList.add( "current" );
      [].forEach.call(this.li, function(item,index){
        item.classList.remove( "current" );
      });
      this.li[this.index].classList.add( "current" );
      this.ul.style.webkitTransform = "translateX(" + ( -this.index * this.width ) + "px)";
          this.ul.style.msTransform = "translateX(" + ( -this.index * this.width ) + "px)";
            this.ul.style.transform = "translateX(" + ( -this.index * this.width ) + "px)";
    },
    touchStart: function( e ) {
      clearInterval( this.play );
      // 记录初始位置
      var touch = e.touches[0];
      this.startX = touch.pageX;
      this.startY = touch.pageY;
    },
    touchMove: function( e ) {
      e.preventDefault();
      var touch = e.touches[0];
      // 记录移动的距离
      var x = touch.pageX - this.startX;
      var y = touch.pageY - this.startY;
      this.translateX = x;
      // 移动时不需要发生过渡动画
      this.ul.style.webkitTransitionDuration = "0ms";
      this.ul.style.webkitTransform = "translateX(" + ( -this.index * this.width + x / 1.2 ) + "px)";
          this.ul.style.msTransform = "translateX(" + ( -this.index * this.width + x / 1.2 ) + "px)";
            this.ul.style.transform = "translateX(" + ( -this.index * this.width + x / 1.2 ) + "px)";
    },
    touchEnd: function( e ) {
      // 判断手指滑动的距离，超出 1/3 时触发滚动
      var canMove = Math.abs( this.translateX ) > this.width / 3;
      if ( canMove ) {
        this.translateX > 0 ? this.index-- : this.index++;
      }
      // 设置inex，手指滑动时不循环滚动
      ( this.index < 0 ) && ( this.index =0 );
      ( this.index >= this.li.length - 1 ) && ( this.index = this.li.length - 1 );
      // 手机离开后重新记录移动距离
      this.translateX = 0;
      this.ul.style.webkitTransitionDuration = "300ms";
          this.ul.style.msTransitionDuration = "300ms";
            this.ul.style.transitionDuration = "300ms";
      // 滚动到需要的位置，并开启自动滚动
      this.move();
      this.autoPlay();
    }
  };
  
  //外部调用
  window.ghSlide = function( container, data ) {
    return function( container, data ){
      window.addEventListener("load", function(){
        this.photoSlide = new slide ( container, data );
      }, false);
      window.addEventListener("resize", function(){
        clearInterval( this.photoSlide.play );
        this.photoSlide = new slide ( container, data );
      }, false);
    }( container, data )
  };
})(window);